﻿using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace mciSendString多线程播放mp3文件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //public static uint SND_ASYNC = 0x0001; // play asynchronously
        //public static uint SND_FILENAME = 0x00020000; //name is file name
        //[DllImport("winmm.dll")]
        //public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback);

        //[STAThread]
        private void btnPlay_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(PlayMp);
            th.IsBackground = true;
            th.Start(@"C:\Users\Simor\Desktop\4.mp3");

            //PlayMp(@"C:\Users\Simor\Desktop\4.mp3");
        }

        
        private void PlayMp(object obj)
        {
            //mciSendString(@"close temp_alias", null, 0, 0);
            //string strFile = "open \"" + obj.ToString() + "\" alias temp_alias";
            //mciSendString(strFile, null, 0, 0);
            //mciSendString("play temp_alias wait", null, 0, 0);
            //mciSendString("close temp_alias", null, 0, 0);  // 关闭

            using (var ms = File.OpenRead(obj.ToString()))
             using (var rdr = new Mp3FileReader(ms))
             using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
            using (var baStream = new BlockAlignReductionStream(wavStream))
               using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
             {
                 waveOut.Init(baStream);
                 waveOut.Play();
                 while (waveOut.PlaybackState == PlaybackState.Playing)
                 {
                     Thread.Sleep(100);
                 }
             }
        }
    }
}
